using IQIGame.Onigao.Framework;
using System.Collections.Generic;

namespace IQIGame.Onigao.Logic
{
    /// <summary>
    /// 延迟行为管理器，注意和延迟服务不同，延迟行为只延迟最基础的操作，不走服务逻辑
    /// </summary>
    public class LgLevelDelayActionManager
    {
        private List<LgLevelDelayActionBase> _delayActionList = new List<LgLevelDelayActionBase>();
        private List<LgLevelDelayActionBase> _tempRemoveActions = new List<LgLevelDelayActionBase>();

        /// <summary>
        /// 添加延迟行为
        /// </summary>
        /// <param name="delayMiliSec"></param>
        /// <param name="action"></param>
        public void AddDelayAction(LgLevelDelayActionBase action)
        {
            if (action.entity == null)
            {
                LogicLog.LogError("添加延迟行为错误，action.entity不能为空。");
                return;
            }
            _delayActionList.Add(action);
        }

        public bool ContainsAction<T>(int entityId) where T : LgLevelDelayActionBase
        {
            foreach (LgLevelDelayActionBase action in _delayActionList)
            {
                if (action is T && !action.isExpired && action.entity.id == entityId)
                {
                    return true;
                }
            }
            return false;
        }

        public void LogicOnUpdate()
        {
            for (int i = 0; i < _delayActionList.Count; i++)
            {
                LgLevelDelayActionBase action = _delayActionList[i];
                action.LogicOnUpdate();
                if (action.isExpired)
                {
                    _tempRemoveActions.Add(action);
                }
            }
            for (int i = 0; i < _tempRemoveActions.Count; i++)
            {
                LgLevelDelayActionBase action = _tempRemoveActions[i];
                _delayActionList.Remove(action);
                ClassPool.PutAutoType(action);
            }
            _tempRemoveActions.Clear();
        }

        public void Dispose()
        {
            for (int i = 0; i < _delayActionList.Count; i++)
            {
                LgLevelDelayActionBase action = _delayActionList[i];
                ClassPool.PutAutoType(action);
            }
            _delayActionList.Clear();
            _tempRemoveActions.Clear();
        }
    }
}
